//
//  PEMEDevBatteryVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/2/27.
//

#import "RHMEDevEMSVC.h"

#import "RHBlockDetailVC.h"
#import "RHBlockPCSParaVC.h"
#import "RHBlockBatteryClusterVC.h"
#import "RHEnergyBlockModel.h"
#import "RHCommonDataCell.h"
#import "RHMEDevMasterVC.h"
#import "RHEMSDetailVC.h"
#import "RHDevEndPointDataModel.h"

#import "SYChartTool.h"
#import "RHDevDataModel.h"

@interface RHMEDevEMSVC ()<UITableViewDelegate,UITableViewDataSource>
//能量组数量
@property (nonatomic, strong) NSArray *emsDataArr;

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic, strong) NSArray *masterDataArr;
@end

@implementation RHMEDevEMSVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
   
    [self setupUI];
    [self getDevRelation];
}

-(NSArray*)createEMSData
{
    NSArray *arr = [SYChartTool loadJsonFileWithName:@"Dev_ems"];
    return [NSArray yy_modelArrayWithClass:[RHDevDataModel class] json:arr];
}

-(void)setupUI
{
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setBackgroundColor:CFTabViewBgColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    _tableView.estimatedRowHeight = 150;
    _tableView.rowHeight = UITableViewAutomaticDimension;

    [_tableView registerClass:[RHCommonDataCell class] forCellReuseIdentifier:CommonNormalCell];
    [_tableView registerClass:[RHCommonDataCell class] forCellReuseIdentifier:CommonStatusCell];
    [_tableView registerClass:[RHCommonDataCell class] forCellReuseIdentifier:CommonIndicatorCell];
    [_tableView registerClass:[RHCommonDataCell class] forCellReuseIdentifier:CommonProgressCell];
    
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(10, 0, 0, 0));
    }];
    
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    }
    _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"没有数据".rh_localized detailStr:@""];
    kWeakSelf;
    [_tableView addHeaderRefresh:^{
        [weakSelf getDevRelation];
    }];
}

#pragma mark ------ network ---------

//获取端点关系
- (void)getDevRelation{
    [QMUITips showLoadingInView:self.view];
    [RHDevEndPointDataModel startGetWithCompletionAPIKey:H_getDevRelation argument:@{@"deviceId":self.deviceModel.deviceId} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
            if(resultModel.code == 200){
                if (ValidDict(request.responseJSONObject[@"data"])) {
                    
                    NSArray *arr = [NSArray yy_modelArrayWithClass:[RHDevEndPointDataModel class] json:request.responseJSONObject[@"data"][@"data"]];
                    //筛选出EMS
                    NSMutableArray *tempArr = [NSMutableArray array];
                    [arr enumerateObjectsUsingBlock:^(RHDevEndPointDataModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        if([obj.type isEqualToString:@"EMU"]){
                            RHDevEndPointDataModel *emuModel = obj;
                            [emuModel.nodes enumerateObjectsUsingBlock:^(RHDevEndPointDataModel  *_Nonnull emsModel, NSUInteger idx, BOOL * _Nonnull stop) {
                                if([emsModel.type isEqualToString:@"EMS"]){
                                    [tempArr addObject:emsModel];
                                }
                            }];
                        }
                        if([obj.type isEqualToString:@"EMS"]){
                            [tempArr addObject:obj];
                        }
                    }];
                    self.emsDataArr = tempArr.copy;
                    if(self.emsDataArr.count>0){
                        [self.emsDataArr enumerateObjectsUsingBlock:^(RHDevEndPointDataModel  *_Nonnull emsModel, NSUInteger idx, BOOL * _Nonnull stop) {
                            emsModel.infoArr = [self createEMSData];
                            [self getDataWithGroupIndex:idx];
                        }];
                    }
                }
                
                
            }
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            [self.tableView endHeaderRefresh];
    }];
}



//获取端点数据
-(void)getDataWithGroupIndex:(NSInteger)index
{
    RHDevEndPointDataModel *emsModel = self.emsDataArr[index];
    [QMUITips showLoadingInView:self.view];
    NSMutableArray *keyCodes = [NSMutableArray array];
    [emsModel.infoArr enumerateObjectsUsingBlock:^(RHDevDataModel  *_Nonnull dataModel, NSUInteger idx, BOOL * _Nonnull stop) {
        [keyCodes addObject:dataModel.keyCode];
    }];
    
    NSDictionary *para = @{@"deviceId":self.deviceModel.deviceId,
                           @"endpointTypeCode":emsModel.type,
                           @"keyCodes":keyCodes,
                           @"endpointSn":emsModel.sn
    };
    [BaseModel startWithCompletionAPIKey:D_getLastEndpointData argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if(resultModel.code == 200){
            if([request.responseObject[@"data"] isKindOfClass:[NSDictionary class]]){
                emsModel.data = request.responseObject[@"data"];
                [self.tableView reloadData];
            }
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
    
}


#pragma mark - UITableViewDelegate,UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 35;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.emsDataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    RHDevEndPointDataModel *emsModel = self.emsDataArr[section];
    return emsModel.infoArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 60;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 60)];
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(15, 10, kUI_WINDOW_W-30, 50)];
    [headView addSubview:bgView];
    bgView.layer.cornerRadius = 8;
    bgView.layer.masksToBounds = YES;
    bgView.layer.maskedCorners = kCALayerMinXMinYCorner|kCALayerMaxXMinYCorner;
    bgView.backgroundColor = [UIColor whiteColor];
    UIImageView *icon = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"dev_ems_icon"]];
    [bgView addSubview:icon];
    
    UIImageView *blockIcon = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"block_icon"]];
    [bgView addSubview:blockIcon];
    
    UIImageView *arrowIcon = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"arrow_2"]];
    [bgView addSubview:arrowIcon];
    
    UILabel *titleLab = [[QMUILabel alloc]init];
    titleLab.font = kBOLDSYSTEMFONT(14);
    titleLab.textColor = kColorRGB(0, 0, 0);
    titleLab.textAlignment = NSTextAlignmentLeft;
    titleLab.text = [NSString stringWithFormat:@"%ld#%@",section+1,@"能量组".rh_localized];
    [bgView addSubview:titleLab];
    
    
    QMUIButton *detailBtn = [[QMUIButton alloc]init];
    [bgView addSubview:detailBtn];
    
    UIView *line = kView;
    line.backgroundColor = kCOLOR_HEX(@"EBEDF0");
    [bgView addSubview:line];
    
    [icon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(@(CGSizeMake(20, 20)));
        make.left.mas_offset(15);
        make.centerY.mas_offset(0);
    }];
    
    [arrowIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(@(CGSizeMake(20, 20)));
        make.right.mas_offset(-15);
        make.centerY.mas_offset(0);
    }];
    [blockIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(@(CGSizeMake(20, 20)));
        make.right.equalTo(arrowIcon.mas_left).offset(-5);
        make.centerY.mas_offset(0);
    }];
    
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(icon.mas_right).offset(15);
        make.centerY.equalTo(icon);
     }];
    
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.offset(1);
        make.bottom.mas_offset(-5);
    }];
    
    [detailBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    kWeakSelf;
    [[detailBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf emsDetail:section];
    }];
    
   return headView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 20;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footer = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 20)];
    footer.backgroundColor = CFTabViewBgColor;
    UIView *subView = [[UIView alloc]initWithFrame:CGRectMake(15, 0, footer.width-30, 10)];
    subView.backgroundColor = [UIColor whiteColor];
    subView.layer.cornerRadius = 8;
    subView.layer.masksToBounds = YES;
    subView.layer.maskedCorners = kCALayerMinXMaxYCorner|kCALayerMaxXMaxYCorner;
    [footer addSubview:subView];
    return footer;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    RHCommonDataCell *cell;
    RHDevEndPointDataModel *emsModel = self.emsDataArr[indexPath.section];
    RHDevDataModel *dataModel = emsModel.infoArr[indexPath.row];
    NSInteger celltype = dataModel.type ;
    if(celltype == CommonCellTypeNormal){
        cell = [tableView dequeueReusableCellWithIdentifier:CommonNormalCell];
    }else if (celltype == CommonCellTypeStatus){
        cell = [tableView dequeueReusableCellWithIdentifier:CommonStatusCell];
    }else if (celltype == CommonCellTypeIndicator){
        cell = [tableView dequeueReusableCellWithIdentifier:CommonIndicatorCell];
    }else if (celltype == CommonCellTypeProgress){
        cell = [tableView dequeueReusableCellWithIdentifier:CommonProgressCell];
    }
    cell.dataModel = dataModel;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    RHDevEndPointDataModel *emsModel = self.emsDataArr[indexPath.section];
    RHEMSDetailVC *detailVC = [[RHEMSDetailVC alloc]init];
    detailVC.title = @"能量组详情".rh_localized;
    detailVC.deviceModel = self.deviceModel;
    detailVC.curEMSModel = emsModel;
    [self.navigationController pushViewController:detailVC animated:YES];
}



-(void)emsDetail:(NSInteger)section
{
    RHDevEndPointDataModel *emsModel = self.emsDataArr[section];
    if(emsModel.nodes.count>0){
        RHMEDevMasterVC *vc = [[RHMEDevMasterVC alloc]init];
        vc.title = [NSString stringWithFormat:@"%ld#%@",section+1,@"能量组".rh_localized];
        vc.deviceModel = self.deviceModel;
        vc.curEmsModel = emsModel;
        vc.masterSectionArr = emsModel.nodes;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        [QMUITips showInfo:@"没有更多的信息".rh_localized];
    }
    
}


#pragma mark - JXCategoryListContentViewDelegate
/**
 实现 <JXCategoryListContentViewDelegate> 协议方法，返回该视图控制器所拥有的「视图」
 */
- (UIView *)listView {
    return self.view;
}


@end
